import EventElement from "./EventElement";

// const ALLElementEventsMap = new WeakMap<EventElement,Map<string, Array<(event:Event)=>any>>>();
const ALLElementEventsMap = new WeakMap<HTMLElement,Map<string, Array<(event:Event)=>any>>>();



export default class EventManage{
    private eventTarget:HTMLElement;
    constructor(eventTarget:HTMLElement){
        this.eventTarget = eventTarget;
    }
    addEventListener(evtName:string,callBack:(event:Event)=>any){
        this.eventTarget.addEventListener(evtName,callBack,false);
        const elementEvents = ALLElementEventsMap.get(this.eventTarget) || new Map<string,Array<(event:Event)=>any>>();
        const currentEvents = elementEvents.get(evtName) || [];
        currentEvents.push(callBack);
        elementEvents.set(evtName,currentEvents);
        ALLElementEventsMap.set(this.eventTarget,elementEvents);
    }

    // addEventListener2(eventTarget: EventElement,evtName:string,callBack:(event:Event)=>any){
    //     const self = this;
    //     this.eventTarget.addEventListener(evtName,function(event: Event){
    //         if(event.target == eventTarget.current){
    //             let taregetEventMap = ALLElementEventsMap.get(eventTarget);
    //             if(taregetEventMap){
    //                 let eventsMap = taregetEventMap.get(evtName);
    //                 if(eventsMap){
    //                     eventsMap.push(callBack);
    //                 }else{
    //                     eventsMap = [callBack];
    //                     taregetEventMap.set(evtName,eventsMap);
    //                 }
    //             }else{
    //                 taregetEventMap = new Map<string, Array<(event:Event)=>any>>();
    //                 taregetEventMap.set(evtName,[callBack]);
    //                 ALLElementEventsMap.set(eventTarget,taregetEventMap);
    //             }
    //         }
    //     },false);
    //     this.eventTarget.addEventListener(evtName,callBack,false);
    //     const elementEvents = ALLElementEventsMap.get(this.eventTarget) || new Map<string,Array<(event:Event)=>any>>();
    //     const currentEvents = elementEvents.get(evtName) || [];
    //     currentEvents.push(callBack);
    //     elementEvents.set(evtName,currentEvents);
    //     ALLElementEventsMap.set(this.eventTarget,elementEvents);
    // }

    destroy() {
        const elementEvents = ALLElementEventsMap.get(this.eventTarget) || new Map<string,Array<(event:Event)=>any>>();
        elementEvents.forEach((events,key)=>{
            events.forEach(evt=>{
                this.eventTarget.removeEventListener(key,evt);
            })
        })
    }
}

